package com.mstar.qs.common;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dchen2
 */
public class DefQsException extends Exception {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2157854319177075243L;

	private Map<String, String> messageStack = new HashMap<String, String>();

	public DefQsException() {
		super();
	}

	public String getKey() {
		if (messageStack.size() == 0)
			return null;
		return messageStack.entrySet().iterator().next().getKey();

	}

	public String getValue() {
		if (messageStack.size() == 0)
			return null;
		return messageStack.entrySet().iterator().next().getValue();

	}

	public String getValue(String key) {
		if (messageStack.size() == 0)
			return null;
		if (messageStack.containsKey(key))
			return messageStack.get(key);
		else
			return null;

	}

	// public DefQsException(String message, Throwable cause,
	// boolean enableSuppression, boolean writableStackTrace) {
	// super(message, cause, enableSuppression, writableStackTrace);
	// }

	public DefQsException(String message, Throwable cause) {
		super(message, cause);
	}

	public DefQsException(String message) {
		super(message);
	}

	public DefQsException(Throwable cause) {
		super(cause);
	}

	public DefQsException(String key, String value) {
		messageStack.put(key, value);
	}

	public static String stackException(Throwable e) {
		StringBuilder sb = new StringBuilder();
		Throwable t = e;
		while (t != null) {
			sb.append(stackSingleException(t));
			t = t.getCause();
		}

		// Throwable[] st = e.getCause();
		// Throwable[] sa;
		// if (st != null && st.length > 0) {
		// sa = new Throwable[st.length + 1];
		// sa[0] = e;
		// System.arraycopy(st, 0, sa, 1, st.length);
		// } else
		// sa = new Throwable[] { e };
		// for (int i = 0; i < st.length; i++) {
		// Throwable t = st[i];
		// sb.append(stackSingleException(t)).append(
		// GlobalConstants.LINE_SEPARATOR);
		// }
		return sb.toString();
	}

	private static String stackSingleException(Throwable e) {
		StringBuilder sb = new StringBuilder();
		sb.append(e.getMessage());
		sb.append(e.toString()).append(GlobalConstants.LINE_SEPARATOR);
		StackTraceElement[] es = e.getStackTrace();
		for (int i = 0; i < es.length; i++) {
			sb.append("\t").append("at ").append(es[i].toString())
					.append(GlobalConstants.LINE_SEPARATOR);
		}
		return sb.toString();
	}
}
